<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>后台管理</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="/css/admin.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://cdn.tiny.cloud/1/ultqulo896fvxj3l2o617lktjikveakzhi2e5rus5uzei7cw/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <a href="/" class="sidebar-home">
                <i class="fas fa-home"></i> 返回主页
            </a>
            <div class="menu-item active">
                <i class="fas fa-chart-line"></i>仪表盘
            </div>
            <div class="menu-item">
                <i class="fas fa-users"></i>用户管理
            </div>
            <div class="menu-item">
                <i class="fas fa-file-alt"></i>内容管理
            </div>
            <div class="menu-item">
                <i class="fas fa-cog"></i>系统设置
            </div>
        </div>

        <div class="main-content">
            <div class="header">
                <div>
                    <h2>欢迎来到后台管理界面</h2>
                    <span id="userInfo"></span>
                </div>
                <button onclick="handleLogout()">
                    <i class="fas fa-sign-out-alt"></i> 退出登录
                </button>
            </div>

            <div id="content">
                <!-- 仪表盘部 -->
                <div id="dashboard">
                    <h3><i class="fas fa-chart-line"></i> 系统概览</h3>
                    <!-- 统计卡片行 -->
                    <div style="margin-top: 20px; display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                        <!-- 用户统计卡片 -->
                        <div class="stat-card">
                            <div class="stat-header">
                                <i class="fas fa-users"></i>
                                <h4>用户统计</h4>
                            </div>
                            <div class="stat-content">
                                <div class="stat-number" id="totalUsers">-</div>
                                <div class="stat-label">总用户数</div>
                            </div>
                        </div>
                        
                        <!-- 管理员统计卡片 -->
                        <div class="stat-card">
                            <div class="stat-header">
                                <i class="fas fa-user-shield"></i>
                                <h4>管理员统计</h4>
                            </div>
                            <div class="stat-content">
                                <div class="stat-number" id="totalAdmins">-</div>
                                <div class="stat-label">管理员数量</div>
                            </div>
                        </div>
                    </div>

                    <!-- 最近登录记录卡片（独立一行） -->
                    <div style="margin-top: 20px;">
                        <div class="stat-card">
                            <div class="stat-header">
                                <i class="fas fa-history"></i>
                                <h4>登录记录</h4>
                            </div>
                            <div class="stat-content">
                                <div id="recentLogins" class="recent-logins">
                                    <!-- 登录记通过 JavaScript 动态加载 -->
                                </div>
                                <div class="pagination" id="loginsPagination">
                                    <!-- 分页控件将通过 JavaScript 动态加载 -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 用户管理部分 -->
                <div id="userManagement" style="display: none;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3><i class="fas fa-users"></i> 用户管理</h3>
                        <button class="btn btn-primary" onclick="showAddUserForm()">
                            <i class="fas fa-plus"></i> 添加用户
                        </button>
                    </div>

                    <div id="userList"></div>

                    <!-- 添加用户模态框 -->
                    <div id="addUserForm" class="modal">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4><i class="fas fa-user-plus"></i> 添加新用户</h4>
                                <span class="close-btn" onclick="hideAddUserForm()">
                                    <i class="fas fa-times"></i>
                                </span>
                            </div>
                            <form onsubmit="handleAddUser(event)">
                                <div class="form-group">
                                    <label>用户名：</label>
                                    <input type="text" id="newUsername" required>
                                </div>
                                <div class="form-group">
                                    <label>密码：</label>
                                    <input type="password" id="newPassword" required>
                                </div>
                                <div class="form-group">
                                    <label>确认密码：</label>
                                    <input type="password" id="newPasswordConfirm" required>
                                </div>
                                <div class="form-group">
                                    <label>角色：</label>
                                    <select id="newRole">
                                        <option value="user">普通用户</option>
                                        <option value="admin">管理员</option>
                                    </select>
                                </div>
                                <div class="form-buttons">
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-check"></i> 确认添加
                                    </button>
                                    <button type="button" class="btn btn-danger" onclick="hideAddUserForm()">
                                        <i class="fas fa-times"></i> 取消
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 修改编辑用户表单部分 -->
                    <div id="editUserForm" class="modal" style="display: none;">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4><i class="fas fa-user-edit"></i> 编辑用户</h4>
                                <span class="close-btn" onclick="hideEditUserForm()">
                                    <i class="fas fa-times"></i>
                                </span>
                            </div>
                            <form onsubmit="handleEditUser(event)">
                                <input type="hidden" id="editUserId">
                                <div class="form-group">
                                    <label>用户名：</label>
                                    <input type="text" id="editUsername" required>
                                </div>
                                <div class="form-group">
                                    <label>新密码：</label>
                                    <input type="password" id="editPassword" placeholder="留空则不修改">
                                </div>
                                <div class="form-group">
                                    <label>确认新密码：</label>
                                    <input type="password" id="editPasswordConfirm" placeholder="留空则不修改">
                                </div>
                                <div class="form-group">
                                    <label>角色：</label>
                                    <select id="editRole">
                                        <option value="user">普通用户</option>
                                        <option value="admin">管理员</option>
                                    </select>
                                </div>
                                <div class="form-buttons">
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-save"></i> 保存修改
                                    </button>
                                    <button type="button" class="btn btn-danger" onclick="hideEditUserForm()">
                                        <i class="fas fa-times"></i> 取消
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- 内容管理部分 -->
                <div id="contentManagement" style="display: none;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3><i class="fas fa-file-alt"></i> 内容管理</h3>
                    </div>

                    <div id="contentList"></div>

                    <!-- 修改编辑内容表单部分 -->
                    <div id="editContentForm" class="modal" style="display: none;">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4><i class="fas fa-edit"></i> 编辑内容</h4>
                                <span class="close-btn" onclick="hideEditContentForm()">
                                    <i class="fas fa-times"></i>
                                </span>
                            </div>
                            <form onsubmit="handleEditContent(event)">
                                <input type="hidden" id="editContentId">
                                <div class="form-group">
                                    <label>标题：</label>
                                    <input type="text" id="editTitle" required>
                                </div>
                                <div class="form-group">
                                    <label>分类：</label>
                                    <select id="editCategory">
                                        <option value="news">新闻</option>
                                        <option value="notice">公告</option>
                                        <option value="article">文章</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>内容：</label>
                                    <textarea id="editContentEditor"></textarea>
                                </div>
                                <div class="form-group">
                                    <label>状态：</label>
                                    <select id="editStatus">
                                        <option value="published">已发布</option>
                                        <option value="unpublished">未发布</option>
                                    </select>
                                </div>
                                <div class="form-buttons">
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-save"></i> 保存修改
                                    </button>
                                    <button type="button" class="btn btn-danger" onclick="hideEditContentForm()">
                                        <i class="fas fa-times"></i> 取消
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 在 body 标签末尾添加 toast 容器 -->
    <div class="toast-container" id="toastContainer"></div>

    <script>
        let currentPage = 1;
        const pageSize = 8;

        async function loadDashboard(page = 1) {
            try {
                const response = await fetch(`/api/dashboard?page=${page}&pageSize=${pageSize}`);
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('totalUsers').textContent = data.totalUsers || '-';
                    document.getElementById('totalAdmins').textContent = data.totalAdmins || '-';
                    
                    // 显示登录记录
                    const recentLoginsHtml = data.recentLogins.map(login => `
                        <div class="login-record">
                            <span class="login-username">${login.username}</span>
                            <span class="login-time">${new Date(login.login_time).toLocaleString()}</span>
                        </div>
                    `).join('');
                    
                    document.getElementById('recentLogins').innerHTML = recentLoginsHtml;
                    
                    // 生成分页控件
                    const totalPages = Math.ceil(data.pagination.total / data.pagination.pageSize);
                    const paginationHtml = generatePagination(data.pagination.current, totalPages);
                    document.getElementById('loginsPagination').innerHTML = paginationHtml;
                }
            } catch (error) {
                console.error('加载仪表盘数据失败:', error);
            }
        }

        // 生成分页控件
        function generatePagination(current, total) {
            let html = '';
            
            // 上一页按钮
            html += `<button onclick="changePage(${current - 1})" ${current === 1 ? 'disabled' : ''}>
                <i class="fas fa-chevron-left"></i>
            </button>`;
            
            // 页码按钮
            for (let i = 1; i <= total; i++) {
                if (i === 1 || i === total || (i >= current - 2 && i <= current + 2)) {
                    html += `<button onclick="changePage(${i})" class="${i === current ? 'active' : ''}">${i}</button>`;
                } else if (i === current - 3 || i === current + 3) {
                    html += `<button disabled>...</button>`;
                }
            }
            
            // 下一页按钮
            html += `<button onclick="changePage(${current + 1})" ${current === total ? 'disabled' : ''}>
                <i class="fas fa-chevron-right"></i>
            </button>`;
            
            return html;
        }

        // 切换页面
        function changePage(page) {
            currentPage = page;
            loadDashboard(page);
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadDashboard(currentPage);
        });

        // 建立 Socket.IO 连接
        const socket = io();

        // 当用户成功登录后，发送连接事件
        socket.on('connect', () => {
            console.log('Socket connected:', socket.id);
            if (socket.userId) {
                socket.emit('store_user_socket', socket.userId);
            }
        });

        // 在 Socket.IO 连接相关代码部分添加
        socket.on('force_logout', (data) => {
            console.log('Received force logout event:', data);
            showToast(data.message, 'info');
            // 确保在跳转前执行清理操作
            socket.disconnect();
            // 延时3秒后跳转
            setTimeout(() => {
                window.location.replace('/login');
            }, 3000);
            return;
        });

        // 修改检查登录状态函数
        async function checkLoginStatus() {
            try {
                const response = await fetch('/api/login/status');
                const data = await response.json();
                if (!data.success) {
                    if (data.message === '您的账号已在其他地方登录') {
                        showToast('您的账号已在其他地方登录，即返回登录页面', 'info');
                    }
                    window.location.replace('/login');
                    return;
                }
                
                document.getElementById('userInfo').textContent = 
                    `当前用户：${data.user.username}`;
                
                if (!socket.userId) {
                    socket.userId = data.user.id;
                    socket.emit('store_user_socket', data.user.id);
                }
                
                // 根据当前 hash 加载对应页面
                const hash = window.location.hash;
                let pageToShow = '仪表盘';
                
                switch (hash) {
                    case '#users':
                        pageToShow = '用户管理';
                        break;
                    case '#content':
                        pageToShow = '内容管理';
                        break;
                    case '#settings':
                        pageToShow = '系统设置';
                        break;
                }
                
                switchPage(pageToShow);
            } catch (error) {
                console.error('检查登录状态失败:', error);
                window.location.replace('/login');
            }
        }

        // 登出处理函数
        async function handleLogout() {
            try {
                console.log('开始发送登出请求');
                
                const response = await fetch('/api/logout', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    credentials: 'same-origin'
                });

                console.log('收到登出响应:', response.status);
                const data = await response.json();
                console.log('登出响应数据:', data);
                
                // 无论成功与否，都执行清理操作
                if (socket && socket.connected) {
                    console.log('断开socket连接');
                    socket.disconnect();
                }

                // 清除本地存储
                console.log('清除本地存储');
                sessionStorage.clear();
                localStorage.clear();
                
                // 清除所有cookie
                document.cookie.split(";").forEach(function(c) { 
                    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
                });
                // 显示提示并延迟跳转
                showToast('正在跳转到登录页面...', 'info');
                await new Promise(resolve => setTimeout(resolve, 1000));
                console.log('重定向到登录页面');
                window.location.href = '/login';
                
            } catch (error) {
                console.error('退出失败:', error);
                showToast('退出失败，请重试\n错误信息: ' + error.message, 'error');
            }
        }

        // 页面加载时检查登录状态
        checkLoginStatus();

        // 显示用户管理页面
        function showUserManagement() {
            document.getElementById('userManagement').style.display = 'block';
            loadUsers();
        }

        // 修改显示添加用户表单函数
        function showAddUserForm() {
            document.getElementById('addUserForm').style.display = 'flex';
            document.body.style.overflow = 'hidden'; // 防止背景滚动
            
            // 清空表单
            document.getElementById('newUsername').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('newPasswordConfirm').value = '';
            document.getElementById('newRole').value = 'user';
        }

        // 修改隐藏添加用户表单函数
        function hideAddUserForm() {
            document.getElementById('addUserForm').style.display = 'none';
            document.body.style.overflow = 'auto'; // 恢复背景滚动
        }

        // 修改添加用户处理函数
        async function handleAddUser(event) {
            event.preventDefault();
            
            const username = document.getElementById('newUsername').value;
            const rawPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('newPasswordConfirm').value;
            const role = document.getElementById('newRole').value;

            // 验证密码
            if (rawPassword !== confirmPassword) {
                showToast('两次输入的密码不一致！', 'error');
                return;
            }

            if (rawPassword.length < 6) {
                showToast('密码长度不能少于6位！', 'error');
                return;
            }

            // 对密码进行哈希处理
            const hashedPassword = CryptoJS.SHA256(rawPassword).toString();

            try {
                const response = await fetch('/api/users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        username, 
                        password: hashedPassword,
                        role,
                        isHashed: true
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    showToast('用户添加成功', 'success');
                    hideAddUserForm();
                    loadUsers();
                } else {
                    showToast(data.message || '添加用户失败', 'error');
                }
            } catch (error) {
                console.error('添加用户失败:', error);
                showToast('添加用户失败', 'error');
            }
        }

        // 添加点击模态框外部关闭功能
        document.getElementById('addUserForm').addEventListener('click', function(e) {
            if (e.target === this) {
                hideAddUserForm();
            }
        });

        // 显示编辑用户表单
        function showEditUserForm(userId, username, role) {
            document.getElementById('editUserId').value = userId;
            document.getElementById('editUsername').value = username;
            document.getElementById('editPassword').value = '';
            document.getElementById('editPasswordConfirm').value = '';
            document.getElementById('editRole').value = role;
            document.getElementById('editUserForm').style.display = 'flex';
            document.body.style.overflow = 'hidden'; // 防背景滚动
        }

        // 隐藏编辑用户表单
        function hideEditUserForm() {
            document.getElementById('editUserForm').style.display = 'none';
            document.getElementById('editPassword').value = '';
            document.getElementById('editPasswordConfirm').value = '';
            document.body.style.overflow = 'auto'; // 恢复背景滚动
        }

        // 点击模态框外部关闭
        document.getElementById('editUserForm').addEventListener('click', function(e) {
            if (e.target === this) {
                hideEditUserForm();
            }
        });

        // 处理编辑用户
        async function handleEditUser(event) {
            event.preventDefault();
            
            const userId = document.getElementById('editUserId').value;
            const username = document.getElementById('editUsername').value;
            const rawPassword = document.getElementById('editPassword').value;
            const confirmPassword = document.getElementById('editPasswordConfirm').value;
            const role = document.getElementById('editRole').value;

            // 如果输入了密码，检查两次输入是否一致
            if (rawPassword) {
                if (rawPassword !== confirmPassword) {
                    showToast('两次输入的密码不一致！', 'error');
                    return;
                }
                if (rawPassword.length < 6) {
                    showToast('密码长度不能少于6位！', 'error');
                    return;
                }
            }

            const data = {
                username,
                role
            };

            if (rawPassword) {
                data.password = CryptoJS.SHA256(rawPassword).toString();
                data.isHashed = true;
            }

            try {
                const response = await fetch(`/api/users/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const responseData = await response.json();
                
                if (responseData.success) {
                    showToast('用户更新成功', 'success');
                    hideEditUserForm();
                    loadUsers();
                } else {
                    showToast(responseData.message, 'error');
                }
            } catch (error) {
                showToast('更新用户失败', 'error');
            }
        }

        // 删除用户
        async function deleteUser(userId) {
            if (!confirm('确定要删除这个用户吗？')) {
                return;
            }

            try {
                const response = await fetch(`/api/users/${userId}`, {
                    method: 'DELETE'
                });

                const data = await response.json();
                
                if (data.success) {
                    showToast('用户删除成功', 'success');
                    loadUsers();
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('删除用户失败', 'error');
            }
        }

        // 修改页面切换函数
        function switchPage(menuText) {
            // 移除所有菜单项的 active 类
            document.querySelectorAll('.menu-item').forEach(menuItem => {
                menuItem.classList.remove('active');
            });
            
            // 隐藏所有内容区域
            document.querySelectorAll('#content > div').forEach(div => {
                div.style.display = 'none';
            });

            // 根据菜单文本设置对应的 hash 和显示相应内容
            let hash = '';
            let targetMenuItem = null;

            switch (menuText.trim()) {
                case '用户管理':
                    hash = '#users';
                    targetMenuItem = document.querySelector('.menu-item:nth-child(3)');
                    document.getElementById('userManagement').style.display = 'block';
                    loadUsers();
                    break;
                case '内容管理':
                    hash = '#content';
                    targetMenuItem = document.querySelector('.menu-item:nth-child(4)');
                    document.getElementById('contentManagement').style.display = 'block';
                    loadContents();
                    break;
                case '系统设置':
                    hash = '#settings';
                    targetMenuItem = document.querySelector('.menu-item:nth-child(5)');
                    // 显示系统设置
                    break;
                default: // 仪表盘
                    hash = '#dashboard';
                    targetMenuItem = document.querySelector('.menu-item:nth-child(2)');
                    document.getElementById('dashboard').style.display = 'block';
                    loadDashboard();
            }

            // 添加 active 类到目标菜单项
            if (targetMenuItem) {
                targetMenuItem.classList.add('active');
            }
            
            // 更新 URL hash
            history.replaceState(null, '', hash);
        }

        // 修改初始处理
        document.addEventListener('DOMContentLoaded', () => {
            // 根据当前 URL hash 显示对应页面
            const hash = window.location.hash;
            let pageToShow = '仪表盘'; // 默认显示仪表盘
            
            switch (hash) {
                case '#users':
                    pageToShow = '用户管理';
                    break;
                case '#content':
                    pageToShow = '内容管理';
                    break;
                case '#settings':
                    pageToShow = '系统设置';
                    break;
            }
            
            switchPage(pageToShow);
        });

        // 修改 hashchange 事件监听器
        window.addEventListener('hashchange', (event) => {
            // 阻止事件的默认行为
            event.preventDefault();
            
            const hash = window.location.hash;
            let pageToShow = '仪表盘'; // 默认显示仪表盘
            
            switch (hash) {
                case '#users':
                    pageToShow = '用户管理';
                    break;
                case '#content':
                    pageToShow = '内容管理';
                    break;
                case '#settings':
                    pageToShow = '系统设置';
                    break;
            }
            
            switchPage(pageToShow);
        });

        // 修改菜单点击事件处理
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', function(event) {
                // 阻止事件冒泡
                event.stopPropagation();
                const menuText = this.textContent.trim();
                switchPage(menuText);
            });
        });

        // 修改 Socket.IO 相关代码部分
        socket.on('dashboard_update', (data) => {
            // 只在仪表盘显示时更新数据
            if (document.getElementById('dashboard').style.display !== 'none') {
                if (data.totalUsers !== undefined) {
                    document.getElementById('totalUsers').textContent = data.totalUsers;
                }
                if (data.totalAdmins !== undefined) {
                    document.getElementById('totalAdmins').textContent = data.totalAdmins;
                }
            }
        });

        // 内容管理相关函数
        async function loadContents() {
            const contentList = document.getElementById('contentList');

            try {
                const response = await fetch('/api/contents');
                const data = await response.json();
                
                if (data.success) {
                    contentList.innerHTML = `
                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>标题</th>
                                    <th>分类</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.contents.map(content => `
                                    <tr>
                                        <td>${content.id}</td>
                                        <td>${content.title}</td>
                                        <td><span class="content-category">${getCategoryName(content.category)}</span></td>
                                        <td><span class="content-status status-${content.status}">${getStatusName(content.status)}</span></td>
                                        <td>${new Date(content.created_at).toLocaleString()}</td>
                                        <td>
                                            <button class="btn btn-primary" onclick="showEditContentForm(${JSON.stringify(content).replace(/"/g, '&quot;')})">
                                                <i class="fas fa-edit"></i> 编辑
                                            </button>
                                            <button class="btn btn-danger" onclick="deleteContent(${content.id})">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    `;
                }
            } catch (error) {
                console.error('加载内容列表失败:', error);
                showToast('加载内容列表失败', 'error');
            }
        }

        function getCategoryName(category) {
            const categories = {
                news: '新闻',
                notice: '公告',
                article: '文章'
            };
            return categories[category] || category;
        }

        function getStatusName(status) {
            const statuses = {
                published: '已发布',
                unpublished: '未发布'
            };
            return statuses[status] || status;
        }

        function showAddContentForm() {
            document.getElementById('addContentForm').style.display = 'block';
        }

        function hideAddContentForm() {
            document.getElementById('addContentForm').style.display = 'none';
            document.getElementById('newTitle').value = '';
            document.getElementById('newContent').value = '';
        }

        async function handleAddContent(event) {
            event.preventDefault();
            
            const title = document.getElementById('newTitle').value;
            const category = document.getElementById('newCategory').value;
            const content = document.getElementById('newContent').value;
            const status = document.getElementById('newStatus').value;

            try {
                const response = await fetch('/api/contents', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        title,
                        category,
                        content,
                        status
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    showToast('内容添加成功', 'success');
                    hideAddContentForm();
                    loadContents();
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('添加内容失败', 'error');
            }
        }

        // 添加一个数组来存储编辑时的待上传图片
        let editPendingImages = [];

        // 修改显示编辑内容表单函数
        function showEditContentForm(content) {
            document.getElementById('editContentId').value = content.id;
            document.getElementById('editTitle').value = content.title;
            document.getElementById('editCategory').value = content.category;
            document.getElementById('editStatus').value = content.status;
            document.getElementById('editContentForm').style.display = 'flex';
            
            // 设置编辑器内容
            tinymce.get('editContentEditor').setContent(content.content);
        }

        // 修改隐藏编辑表单函数
        function hideEditContentForm() {
            document.getElementById('editContentForm').style.display = 'none';
            document.body.style.overflow = 'auto'; // 恢复背景滚动
            // 清空编辑器内容
            tinymce.get('editContentEditor').setContent('');
        }

        // 点击模态框外部关闭
        document.getElementById('editContentForm').addEventListener('click', function(e) {
            if (e.target === this) {
                hideEditContentForm();
            }
        });

        // 修改编辑内容处理函数
        async function handleEditContent(event) {
            event.preventDefault();
            
            try {
                const contentId = document.getElementById('editContentId').value;
                const title = document.getElementById('editTitle').value;
                const category = document.getElementById('editCategory').value;
                const status = document.getElementById('editStatus').value;
                const content = tinymce.get('editContentEditor').getContent();

                const response = await fetch(`/api/contents/${contentId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        title,
                        category,
                        content,
                        status
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    showToast('内容更新成功', 'success');
                    hideEditContentForm();
                    loadContents();
                } else {
                    throw new Error(data.message || '更新失败');
                }
            } catch (error) {
                showToast(error.message || '更新内容失败', 'error');
                console.error('更新失败:', error);
            } 
        }

        // 页面加载时初始化编辑器
        document.addEventListener('DOMContentLoaded', function() {
            initEditor('#editContentEditor');
        });

        // 初始化编辑器
        function initEditor(selector) {
            tinymce.init({
                selector: selector,
                height: 500,
                plugins: [
                    'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
                    'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                    'insertdatetime', 'media', 'table', 'help', 'wordcount'
                ],
                toolbar: 'undo redo | blocks | ' +
                    'bold italic forecolor | alignleft aligncenter ' +
                    'alignright alignjustify | bullist numlist outdent indent | ' +
                    'removeformat | image | help',
                language: 'zh_CN', // 使用中文界
                images_upload_url: '/api/upload', // 图片上传接口
                images_upload_handler: async function (blobInfo, progress) {
                    try {
                        const formData = new FormData();
                        formData.append('image', blobInfo.blob(), blobInfo.filename());

                        const response = await fetch('/api/upload', {
                            method: 'POST',
                            body: formData
                        });

                        const data = await response.json();
                        if (data.success) {
                            return data.url;
                        }
                        throw new Error('上传失败');
                    } catch (error) {
                        console.error('图片上传失败:', error);
                        throw error;
                    }
                },
                file_picker_types: 'image',
                content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px; }',
                setup: function(editor) {
                    editor.on('change', function() {
                        // 更新隐藏的 textarea
                        document.getElementById('editContent').value = editor.getContent();
                    });
                }
            });
        }

        // 添加删除内容的函数
        async function deleteContent(contentId) {
            if (!confirm('确定要删除这个内容吗？')) {
                return;
            }

            try {
                const response = await fetch(`/api/contents/${contentId}`, {
                    method: 'DELETE'
                });

                const data = await response.json();
                
                if (data.success) {
                    showToast('内容删除成功', 'success');
                    loadContents(); // 重新加载内容列表
                } else {
                    throw new Error(data.message || '删除失败');
                }
            } catch (error) {
                showToast(error.message || '删除内容失败', 'error');
                console.error('删除失败:', error);
            }
        }

        // 添加页面可见性变化监听
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden && socket.userId) {
                socket.connect();
                socket.emit('user_connected', socket.userId);
                socket.emit('store_user_socket', socket.userId);
            }
        });

        // 添加页面关闭前处理
        window.addEventListener('beforeunload', () => {
            if (socket.connected) {
                socket.disconnect();
            }
        });

        // 加载用户列表函数
        async function loadUsers() {
            const userList = document.getElementById('userList');
            const isFirstLoad = !userList.innerHTML;
            if (isFirstLoad) {
            }

            try {
                const response = await fetch('/api/users');
                const data = await response.json();
                
                if (data.success) {
                    userList.innerHTML = `
                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>角色</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.users.map(user => `
                                    <tr>
                                        <td>${user.id}</td>
                                        <td>${user.username}</td>
                                        <td>
                                            <span class="badge ${user.role === 'admin' ? 'badge-admin' : 'badge-user'}">
                                                ${user.role === 'admin' ? '管理员' : '普通用户'}
                                            </span>
                                        </td>
                                        <td>${new Date(user.created_at).toLocaleString()}</td>
                                        <td>
                                            <button class="btn btn-primary" onclick="showEditUserForm(${user.id}, '${user.username}', '${user.role}')">
                                                <i class="fas fa-edit"></i> 编辑
                                            </button>
                                            <button class="btn btn-danger" onclick="deleteUser(${user.id})">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    `;
                }
            } catch (error) {
                console.error('加载用户列表失败:', error);
                showToast('加载用户列表失败', 'error');
            }
        }

        // 显示提示框的函数
        function showToast(message, type = 'info') {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            
            let icon = '';
            switch(type) {
                case 'success':
                    icon = 'check-circle';
                    break;
                case 'error':
                    icon = 'times-circle';
                    break;
                default:
                    icon = 'info-circle';
            }
            
            toast.innerHTML = `
                <i class="fas fa-${icon} toast-icon"></i>
                <div class="toast-message">${message}</div>
            `;
            
            container.appendChild(toast);
            
            // 3秒后移除提示框
            setTimeout(() => {
                toast.addEventListener('animationend', () => {
                    container.removeChild(toast);
                });
            }, 3000);
        }
    </script>
</body>
</html> 